package com.tracking.application.fragments;


import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import com.tracking.application.R;
import com.tracking.application.activities.TabsActivity;
import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Kamil.O
 * Description: Graph tab activity
 * Date: 18.11.13
 * Time: 22:56
 */
public class GraphFragment extends Fragment {
    private TabsActivity tabsActivity;
    private GraphicalView mChartView = null;
    private RelativeLayout layout;
    private RelativeLayout.LayoutParams params;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            tabsActivity = (TabsActivity) activity;
        } catch(ClassCastException e) {
            throw new ClassCastException(activity.toString() + " must implement DataPullingInterface");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.graph_activity, container, false);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        mChartView = null;
        params = null;
        if (layout != null) layout.removeAllViews();
        drawGraph();
    }

    private void drawGraph() {
        /*
        * dystans
        * */
        String[] titles = new String[] { getString(R.string.speed_info) };
        List<double[]> axisX = new ArrayList<double[]>();
        for (int i = 0; i < titles.length; i++) {
            axisX.add(getDoubles(tabsActivity.getDistanceListSumForGraphKm()));
        }

        /*
        * Predkosc
        * */
        List<double[]> values = new ArrayList<double[]>();
        values.add(getDoubles(tabsActivity.getSpeedListKm()));

        int[] colors = new int[] { Color.BLUE, Color.YELLOW };
        PointStyle[] styles = new PointStyle[] { PointStyle.POINT, PointStyle.POINT };
        XYMultipleSeriesRenderer renderer = new XYMultipleSeriesRenderer(2);
        setRenderer(renderer, colors, styles);
        int length = renderer.getSeriesRendererCount();
        for (int i = 0; i < length; i++) {
            XYSeriesRenderer r = (XYSeriesRenderer) renderer.getSeriesRendererAt(i);
            r.setLineWidth(3f);
        }
        setChartSettings(renderer, getString(R.string.graph_title), getString(R.string.distance), getString(R.string.speed), 0,
                tabsActivity.getMaxSpeed()+10, Color.LTGRAY, Color.LTGRAY);
        renderer.setXLabels(12);
        renderer.setYLabels(10);
        renderer.setShowGrid(true);
        renderer.setXLabelsAlign(Paint.Align.RIGHT);
        renderer.setYLabelsAlign(Paint.Align.RIGHT);
        renderer.setZoomButtonsVisible(true);
        renderer.setPanLimits(new double[]{-10, 20, -10, 40});
        renderer.setZoomLimits(new double[]{-10, 20, -10, 40});
        renderer.setZoomRate(1.05f);
        renderer.setLabelsColor(Color.WHITE);
        renderer.setXLabelsColor(Color.GREEN);
        renderer.setYLabelsColor(0, colors[0]);
        renderer.setYLabelsColor(1, colors[1]);

        renderer.setYTitle(getString(R.string.altitude), 1);
        renderer.setYAxisAlign(Paint.Align.RIGHT, 1);
        renderer.setYLabelsAlign(Paint.Align.LEFT, 1);

        XYMultipleSeriesDataset dataset = buildDataset(titles, axisX, values);

        /*
        * Wysokosc
        * */
        values.clear();
        values.add(getDoubles(tabsActivity.getAltitudeListPrecision()));
        addXYSeries(dataset, new String[] { getString(R.string.altitude_info) }, axisX, values, 1);

        mChartView = ChartFactory.getCubeLineChartView(tabsActivity, dataset, renderer, 0.3f);

        params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        mChartView.setLayoutParams(params);
        layout = (RelativeLayout) tabsActivity.findViewById(R.id.chartsRelativeLayout);
        layout.addView(mChartView);
    }

    private double[] getDoubles(List<Double> list) {
        double tempX[] = new double[list.size()];
        for(int i = 0; i < tempX.length; i++){
            tempX[i] = list.get(i);
        }
        return tempX;
    }

    protected void setRenderer(XYMultipleSeriesRenderer renderer, int[] colors, PointStyle[] styles) {
        renderer.setAxisTitleTextSize(20);
        renderer.setChartTitleTextSize(20);
        renderer.setLabelsTextSize(15);
        renderer.setLegendTextSize(20);
        renderer.setPointSize(5f);
        renderer.setMargins(new int[] { 40, 50, 35, 40 });
        int length = colors.length;
        for (int i = 0; i < length; i++) {
            XYSeriesRenderer r = new XYSeriesRenderer();
            r.setColor(colors[i]);
            r.setPointStyle(styles[i]);
            renderer.addSeriesRenderer(r);
        }
    }

    protected void setChartSettings(XYMultipleSeriesRenderer renderer, String title, String xTitle,
                                    String yTitle, double yMin, double yMax, int axesColor,
                                    int labelsColor) {
        renderer.setChartTitle(title);
        renderer.setXTitle(xTitle);
        renderer.setYTitle(yTitle);
        renderer.setYAxisMin(yMin);
        renderer.setYAxisMax(yMax);
        renderer.setAxesColor(axesColor);
        renderer.setLabelsColor(labelsColor);
    }

    protected XYMultipleSeriesDataset buildDataset(String[] titles, List<double[]> xValues,
                                                   List<double[]> yValues) {
        XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
        addXYSeries(dataset, titles, xValues, yValues, 0);
        return dataset;
    }

    public void addXYSeries(XYMultipleSeriesDataset dataset, String[] titles, List<double[]> xValues, List<double[]> yValues, int scale) {
        int length = titles.length;
        for (int i = 0; i < length; i++) {
            XYSeries series = new XYSeries(titles[i], scale);
            double[] xV = xValues.get(i);
            double[] yV = yValues.get(i);
            int seriesLength = xV.length;
            for (int k = 0; k < seriesLength; k++) {
                series.add(xV[k], yV[k]);
            }
            dataset.addSeries(series);
        }
    }

    private String getString(Context context, int id){
        return context.getResources().getString(id);
    }
}
